package com.zxy.springboot_vue.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.springboot_vue.config.AjaxResult;
import com.zxy.springboot_vue.entity.Menu;
import com.zxy.springboot_vue.entity.MenuRole;
import com.zxy.springboot_vue.service.IMenuRoleService;
import com.zxy.springboot_vue.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lenovo
 * @since 2021-10-19
 */
@RestController
@RequestMapping("/menu-role")
public class MenuRoleController {

    @Autowired
    private IMenuRoleService menuRoleService;
    @Autowired
    private IMenuService menuService;

    @RequestMapping("selectById")
    public AjaxResult selectById(Integer rid){
        QueryWrapper<MenuRole> wrapper = null;
        if(rid!=null){
            wrapper = new QueryWrapper<>();
            wrapper.eq("rid",rid);
        }
        /*查询中间表*/
        List<MenuRole> list = menuRoleService.list(wrapper);
        /*去查询总菜单中对应的菜单*/
        ArrayList<Integer> list1 = new ArrayList<>();
        for (MenuRole menuRole : list) {
            Menu menu = menuService.getById(menuRole.getMid());
            /*不包括根节点*/
            if(menu.getLevel()!=1){
                list1.add(menu.getId());
            }
        }
        return AjaxResult.ok(list1);
    }

    @PostMapping("saveMenuRole")
    public AjaxResult saveMenuRole(@RequestBody MenuRole menuRole){
        System.out.println("添加菜单的参数"+menuRole);;
        System.err.println(menuRole.getMids());
        QueryWrapper<MenuRole> wrapper = new QueryWrapper<>();
        wrapper.eq("rid",menuRole.getRid());
        //删除该角色对应的菜单
        //先删除在进行添加
        menuRoleService.remove(wrapper);

        //向中间表中进行添加
        MenuRole menuRole1 = new MenuRole();

        for (Integer mid : menuRole.getMids()) {
            if(mid!=1){
                menuRole1.setMid(mid);
                menuRole1.setRid(menuRole.getRid());
                menuRoleService.save(menuRole1);
            }

        }

        return AjaxResult.ok();
    }



}
